
package site;

import constans.SizeConstans;
import database.ConnectionDB;
import database.DatabaseMysql;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;


public class TopRequest extends ProcessRequest {

    private static final int windowSize = 20;
    private final String databaseHost;
    private final String databaseName;
    private final String databasePassword;
    private final String databaseUser;


    public TopRequest(ServletContext context){
        databaseHost      = context.getInitParameter("DatabaseHost");
        databaseName      = context.getInitParameter("DatabaseName");
        databasePassword  = context.getInitParameter("DatabasePassword");
        databaseUser      = context.getInitParameter("DatabaseUser");
    }

    
    @Override
    protected void process(HttpServletResponse response, String[] arguments) {

        response.setContentType("text/html; charset=\"UTF-8\"");

        PrintWriter out = null;
        ConnectionDB connectionDB =null;
        DecimalFormat decimalFormat = new DecimalFormat("#.#");

        try {

            out=  response.getWriter();

            connectionDB =  new DatabaseMysql(databaseHost,databaseUser,databasePassword ,databaseName).getConnection();

            String language = arguments[0];

            out.println("<HTML><HEAD>");
            out.println("<a href=\"http://www.arquivo.pt\"><img src=\"http://arquivo-web.fccn.pt/logo.jpg\" alt=\"Logotipo  AWP\" border=\"0\"></a>");
            out.println("<META http-equiv=\"content-language\" content=\""+language+"\">");
            
            if(language.equals("en")){
                out.println("<META name=\"description\" content=\"List of the rARC top contributors.\">");
                out.println("<META name=\"keywords\" content=\"rARC, top, contributors\">");
                out.println("<TITLE>Top 20 rARC contributors</TITLE>");
            }
            else{
                out.println("<META name=\"description\" content=\"Lista dos contribuidores mais generosos do rARC.\">");
                out.println("<META name=\"keywords\" content=\"rARC, tabela, contribuidores\">");
                out.println("<TITLE>Tabela dos 20 maiores contribuidores do rARC</TITLE>");
            }

            out.println("</HEAD><BODY>");

             if(language.equals("en")){
                out.println("<CENTER><H1>Top 20 rARC contributors</H1></CENTER>");
                out.println("This table shows the 20 contributors that have offered more disk space.<p>");
             }
            else{
                out.println("<CENTER><H1>Os 20 maiores contribuidores do rARC</H1></CENTER>");
                out.println("A seguinte tabela apresenta os 20 contribuidores que disponibilizam mais espaço.<p>");
            }

           if(language.equals("en"))
                out.println("<a href=\"http://arquivo-web.fccn.pt/rarc/show/list/?l="+language+"&o=0\">Complete list</a> ");
            else
                out.println("<a href=\"http://arquivo-web.fccn.pt/rarc/show/list/?l="+language+"&o=0\">Lista completa</a> ");

            out.println("<HR SIZE=1>");
            out.println("<TABLE BORDER=1 WIDTH =\"100%\">");

             if(language.equals("en"))
                out.println("<tr><th>Rank</th><th>Name</th><th>Contributor since</th><th>Offered space</th></tr>");
             else
                 out.println("<tr><th>Posição</th><th>Nome</th><th>Contribuidor desde</th><th>Espaço oferecido</th></tr>");

            int total = 1;

           String query = "SELECT User.name, User.initDate, Identifier.offeredSpace " +
                   "FROM User, Identifier " +
                   "WHERE User.email = Identifier.email AND Identifier.offeredSpace > 0 AND  Identifier.lastUpdate > (SELECT DATE_SUB(curdate(), INTERVAL 1 MONTH)) " +
                   "AND Identifier.numberCapsules > 2" +
                   "ORDER BY Identifier.offeredSpace DESC limit "+windowSize;
           
            ResultSet resultSet = connectionDB.executeSelect(query);

            while(resultSet.next()){

                out.println("<tr>");
                out.println("<td align=center>"+total+"</td>");//ranking
                out.println("<td align=center>"+resultSet.getString(1)+"</td>");//name
                out.println("<td align=center>"+resultSet.getDate(2).toString()+"</td>");//participant since
                out.println("<td align=center>"+decimalFormat.format(resultSet.getDouble(3)/SizeConstans.GByte)+" GB</td>");//offered space
                out.println("</tr>");

                total++;
            }

            out.println("</TABLE></CENTER>");
            out.println("<HR SIZE=1>");

              if(language.equals("en"))
                out.println("<a href=\"http://arquivo-web.fccn.pt/rarc/show/list/?l="+language+"&o=0\">Complete list</a> ");
             else
                 out.println("<a href=\"http://arquivo-web.fccn.pt/rarc/show/list/?l="+language+"&o=0\">Lista completa</a> ");

            out.println("</BODY></HTML>");
            out.flush();
            out.close();

            connectionDB.closeStatement();

        } catch (SQLException ex) {
            Logger.getLogger(TopRequest.class.getName()).log(Level.SEVERE, null, ex);
        }  catch (IOException ex) {
            Logger.getLogger(TopRequest.class.getName()).log(Level.WARNING, null, ex);
        } finally{
            if(out!=null){
                   out.close();
            }
            if(connectionDB!=null){
                try {
                    connectionDB.close();
                } catch (SQLException ex) {}
            }
        }

    }

}
